package com.zzjc.web.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileFilter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;



@Slf4j
public class DirSearchUtil {
    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    //    private String searchDir = "/var/www/html/njgt/rec/live/video/history";
    private String searchDir;
    private File[] fileList = null;// 保存文件列表,过滤掉目录
    private List<String> resultList;
    private Map<String, Object> resultSearch;
    private String splitToken1 = "_";
    private String splitToken2 = "-";

    public static DirSearchUtil build() {
        return new DirSearchUtil();
    }

    public Map<String, Object> searchDir(String pre, String year) {
        return this.searchDir(pre, year, null, null, null, null);
    }

    public Map<String, Object> searchDir(String pre, String year, String month) {
        return this.searchDir(pre, year, month, null, null, null);
    }

    public Map<String, Object> searchDir(String pre, String year, String month, String day) {
        return this.searchDir(pre, year, month, day, null, null);
    }

    public Map<String, Object> searchDir(String pre, String year, String month, String day, String hour) {
        return this.searchDir(pre, year, month, day, hour, null);
    }

    public Map<String, Object> searchDir(String pre, String year, String month, String day, String hour, String minute) {
        //编写一条匹配脚本
        year = StringUtils.isBlank(year) ? "\\d+" : year;
        month = StringUtils.isBlank(month) ? "\\d+" : month;
        day = StringUtils.isBlank(day) ? "\\d+" : day;
        hour = StringUtils.isBlank(hour) ? "\\d+" : hour;
        minute = StringUtils.isBlank(minute) ? "\\d+" : minute;
        String match = pre + splitToken1 + year + splitToken2 + month + splitToken2 + day + splitToken2 + hour + splitToken2 + minute;
        log.info("match:" + match);
        this.getFiles();
        resultList = new ArrayList<String>();
        for (File file : fileList) {
            if (Pattern.matches(match, file.getName())) {
                resultList.add(file.getName());
            }
        }
        resultSearch = new HashMap<>();
        return resultSearch;
    }

    public Map<String, Object> searchDirByPage(String searchDir, String sequenceId, String beganDate, String endedDate, Integer pageNum, Integer pageSize) {
        log.info("searchDir:" + searchDir + " sequenceId：" + sequenceId + " beganDate:" + beganDate + " endedDate:" + endedDate + " pageNum:" + pageNum + " pageSize:" + pageSize);
        this.searchDir = searchDir;
        log.info("开始检索:" + dtf.format(LocalDateTime.now()));
        resultSearch = new HashMap<>();
        /**1.拼接时间搜索范围*/
//        /**开始时间*/
//        String BeganDate = dateTimeList.get(0) + "-" + dateTimeList.get(1) + "-" + dateTimeList.get(2)
//                + " " + dateTimeList.get(3) + ":" + dateTimeList.get(4) + ":" + dateTimeList.get(5);
//        /**结束时间*/
//        String EndedDate = dateTimeList.get(6) + "-" + dateTimeList.get(7) + "-" + dateTimeList.get(8)
//                + " " + dateTimeList.get(9) + ":" + dateTimeList.get(10) + ":" + dateTimeList.get(11);
//		log.info("BeganDate:"+BeganDate);
//		log.info("EndedDate"+EndedDate);
        /**2.筛选视频路径*/
        /**获取所有文件路径*/
        this.getFiles();
        log.info("全部列表:" + dtf.format(LocalDateTime.now()));
        if (fileList == null) {
            return null;
        }
        resultList = new ArrayList<String>();

        for (File file : fileList) {
            /** 文件名匹配:例如:EJQ-CAMERA-N-001_2022-10-18-14-15-42.mp4*/
            String regex = "^[a-zA-Z0-9[-]]*[_]\\d{4}[-]\\d{2}[-]\\d{2}[-]\\d{2}[-]\\d{2}[-]\\d{2}\\.(flv|mp4|ogv|avi)$";
            String fileName = file.getName();
            if ("".equals(sequenceId) || sequenceId == null) {
                if (!fileName.matches(regex)) {
                    continue;
                } else {
                    this.addFile(file, beganDate, endedDate);
                }
            } else {
                if (!fileName.matches(regex) || !StringUtils.substringBefore(fileName, "_").equals(sequenceId)) {
                    continue;
                } else {
                    this.addFile(file, beganDate, endedDate);
                }
            }
//			log.info("fileList:"+file.getPath());
//			log.info("fileList:"+fileDate);
//			log.info(DateUtils.parseDate(fileDate));
        }
        log.info("匹配文件" + resultList.size() + "个:" + dtf.format(LocalDateTime.now()));
        if (resultList.size() == 0) {
            return null;
        }
//		log.info("resultList:"+resultList);
        /**3.对resultList按时间进行排序*/
        resultSearch.put("total", resultList.size());
        String str;
//        //外层循环length-1次
//        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
//        for (int i = 0; i < resultList.size() - 1; i++) {
//
//            //外层每循环一次最后都会排好一个数
//            //所以内层循环length-1-i次
//            for (int j = 0; j < resultList.size() - 1 - i; j++) {
//                String str1 = StringUtils.substringBefore(
//                        StringUtils.substringAfterLast(resultList.get(j), "_"), "."
//                ).replace("-", "");
//                String str2 = StringUtils.substringBefore(
//                        StringUtils.substringAfterLast(resultList.get(j + 1), "_"), "."
//                ).replace("-", "");
//                if (Long.valueOf(str1) <= Long.valueOf(str2)) {
//                    str = resultList.get(j);
//                    resultList.set(j, resultList.get(j + 1));
//                    resultList.set(j + 1, str);
//                }
//            }
//        }
        this.quickSort(resultList, 0, resultList.size() - 1);

//		log.info("resultList:"+resultList);
        if (pageNum == null & pageSize == null) {
            resultSearch.put("resultList", resultList);
            return resultSearch;
        }
        log.info("分页排序:" + dtf.format(LocalDateTime.now()));
        resultList = resultList.subList((pageNum - 1) * pageSize, Math.min(resultList.size(), pageNum * pageSize));
        resultSearch.put("resultList", resultList);
        return resultSearch;
    }

    private void addFile(File file, String beganDate, String endedDate) {
        String str = StringUtils.substringBefore(
                StringUtils.substringAfterLast(file.getPath(), "_"), "."
        );
        List<String> fileDateList = Arrays.asList(str.split("-"));
        String fileDate = fileDateList.get(0) + "-" + fileDateList.get(1) + "-" + fileDateList.get(2)
                + " " + fileDateList.get(3) + ":" + fileDateList.get(4) + ":" + fileDateList.get(5);
        if ((DateUtils.parseDate(fileDate).getTime() - DateUtils.parseDate(beganDate).getTime()) > 0
                && (DateUtils.parseDate(endedDate).getTime() - DateUtils.parseDate(fileDate).getTime()) >= 0) {
            resultList.add(file.getPath());
        }
    }

    /**
     * 获取文件列表
     */
    public File[] getFiles() {
        if (searchDir == null) {
            File file = new File(searchDir);
            fileList = new File[1];
            fileList[0] = file;
            return fileList;
        }
        fileList = new File(searchDir).listFiles(new FileFilter() {

            /**使用过滤器过滤掉目录*/
            @Override
            public boolean accept(File pathname) {
                if (pathname.isDirectory()) {
                    return false;
                } else
                    return true;
            }
        });
        /**
         * 循环输出所有历史视频路径
         */
//        for (File file : fileList) {
//            String fileDate = StringUtils.substringBefore(
//                    StringUtils.substringAfterLast(file.getPath(), "_"), "."
//            );
//
//			log.info("fileList:"+file.getName());
//			log.info("fileList:"+fileDate);
//        }
        return fileList;
    }

    /**
     * 快速排序
     *
     * @param resultList
     * @param low
     * @param high
     */
    public void quickSort(List<String> resultList, int low, int high) {
        int i = low;
        int j = high;
        String str;
        Long povit = Long.valueOf(StringUtils.substringBefore(
                StringUtils.substringAfterLast(resultList.get((low + high) / 2), "_"), "."
        ).replace("-", ""));
        while (i < j) {
            while (Long.valueOf(StringUtils.substringBefore(
                    StringUtils.substringAfterLast(resultList.get(i), "_"), "."
            ).replace("-", "")) < povit) {
                i++;
            }
            while (Long.valueOf(StringUtils.substringBefore(
                    StringUtils.substringAfterLast(resultList.get(j), "_"), "."
            ).replace("-", "")) > povit) {
                j--;
            }
            if (i <= j) {
                str = resultList.get(i);
                resultList.set(i, resultList.get(j));
                resultList.set(j, str);
                i++;
                j--;
            }
        }
        if (j > low) {
            quickSort(resultList, low, j);
        }
        if (i < high) {
            quickSort(resultList, i, high);
        }
    }
}
